package com.jmp.security.grant.jxsApp;

import com.jmp.base.dto.SmsCaptchaCheckRequest;
import com.jmp.base.dto.SmsCaptchaCheckResponse;
import com.jmp.base.dto.SmsCodeEnums;
import com.jmp.feign.SmsFeign;
import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.UserDetail;
import com.jmp.security.base.UserDetailService;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.config.SecurityProperties;
import one.stand.model.ResultModel;
import one.stand.model.User;
import one.stand.service.UserService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;

import java.util.Objects;

@Slf4j
public class JxsAppSmsUserDetailServiceImpl implements UserDetailService<JxsAppSmsRequestDetail> {
    private SecurityProperties securityProperties;
    private UserAdminService userAdminService;
    private SmsFeign smsFeign;
    private UserService userService;

    public JxsAppSmsUserDetailServiceImpl(SecurityProperties securityProperties, SmsFeign smsFeign, UserAdminService userAdminService, UserService userService) {
        this.securityProperties = securityProperties;
        this.smsFeign = smsFeign;
        this.userAdminService = userAdminService;
        this.userService = userService;
    }

    @Override
    public UserDetail get(JxsAppSmsRequestDetail requestDetail, ClientDetail clientDetail) {
        if (securityProperties.isSms()) {//开启验证
            ResultModel<SmsCaptchaCheckResponse> checkResult = smsFeign.captchaCheck(SmsCaptchaCheckRequest.builder()
                    .phone(requestDetail.getPhone())
                    .type(SmsCodeEnums.login_sms_jxs.getCode())
                    .captcha(requestDetail.getSmsCode())
                    .build());
            AssertUtil.isTrue(checkResult);
            AssertUtil.isTrue(checkResult.getData().isSuccess(), ResultEnum.PARAM_CHECK, "验证码错误");
        }

        //user info
        User userModel = userService.getByPhone(requestDetail.getPhone(), null);
        Integer userId;
        if (Objects.isNull(userModel)) {
            Integer companyId = clientDetail.getCompanyAccountModel().getCompanyId();
            userId = saveUser(companyId, requestDetail.getPhone(), requestDetail);
        } else {
            userId = userModel.getUserId();
        }

        userModel = userAdminService.getByUserId(userId);//重新获取最新User信息
        UserDetail userDetail = new UserDetail();
        userDetail.setUserModel(userModel);
        return userDetail;
    }

    private Integer saveUser(Integer companyId, String phone, JxsAppSmsRequestDetail requestDetail) {
        User inModel = new User();
        inModel.setPhone(phone);
        inModel.setNickeName(phone);
        inModel.setEnterpriseId(companyId);
        userService.saveUser(inModel);
        return inModel.getUserId();
    }
}
